package se.rende.myrss.data;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXSource;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.ccil.cowan.tagsoup.Parser;
import org.xml.sax.InputSource;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
import org.xml.sax.XMLReader;

import com.sun.syndication.feed.synd.SyndEntry;

public class IncludeSlashdotCommentsFilterType implements FilterType {
	private int commentNumber = 0;
	private Transformer transformer;
	private XMLReader reader;

	public IncludeSlashdotCommentsFilterType()
			throws TransformerConfigurationException,
			SAXNotRecognizedException, SAXNotSupportedException {
		TransformerFactory tFactory = TransformerFactory.newInstance();
		transformer = tFactory.newTransformer(new StreamSource(getClass()
				.getResourceAsStream("format-comment.xsl")));
		reader = new Parser();
	}

	@Override
	public String getId() {
		return "inclsdcomments";
	}

	@Override
	public String execute(String input, List<String> params, SyndEntry syndEntry) {
		commentNumber++;
		if (commentNumber <= -1) {
			ByteArrayOutputStream os = new ByteArrayOutputStream();
			InputStream is = null;
			try {
				URL feedUrl = new URL(syndEntry.getLink());
				URLConnection urlConnection = feedUrl.openConnection();
				urlConnection.setReadTimeout(30000);
				urlConnection.setConnectTimeout(10000);
				urlConnection.setDoOutput(true);
				is = urlConnection.getInputStream();
				if (urlConnection instanceof HttpURLConnection) {
					HttpURLConnection httpConnection = (HttpURLConnection) urlConnection;
					int code = httpConnection.getResponseCode();
					if (code == 200) {
	
						SAXSource source = new SAXSource(reader, new InputSource(is));
	
						StreamResult result = new StreamResult(os);
	
						transformer.transform(source, result);
						return input + os.toString("utf-8");
					}
				}
			} catch (MalformedURLException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (TransformerException e) {
				e.printStackTrace();
			} finally {
				if (is != null) {
					try {
						is.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}
		return input;
	}

	@Override
	public void startBatch() {
		commentNumber = 0;
	}
}
